﻿jQuery.ei = {
    dateFormatter: function (value, row, index) {
        if (!value) return ''
        return moment(value).format('YYYY-MM-DD')
    },
    timeFormatter: function (value, row, index) {
        if (!value) return ''
        return moment(value).format('YYYY-MM-DD HH:mm:ss');
    },
    shortTimeFormatter: function (value, row, index) {
        if (!value) return ''
        return moment(value).format('HH:mm:ss');
    },
    boolFormatter: function (value, row, index) {
        if (value == 1) {
            return '是';
        } else if (value == 0) {
            return '否';
        } else {
            return '';
        }
    },
    imgFormatter: function (value, row, index) {
        if (value) {
            if (value.indexOf("/") != -1) {
                return '<img src="{0}" alt="图片" style="width:100px;height:30px" onclick="$.dm.showPic(this.src)" />'.format(value);;
            } else {
                return value;
            }
        } else {
            return '';
        }

    },
    herfFormatter: function (value, row, index) {
        if (value) {
            return '<a href="{0}" target="blank">{0}<a>'.format(value);
        } else {
            return '';
        }
    },
    fileFormatter: function (value, row, index) {
        if (value) {
            var herf = "/api/services/app/File/DownFileForUpload?filePath=" + value;
            if (value.startsWith("http")) {
                herf = value;
            }
            return '<a href="{0}" target="blank">下载<a>'.format(herf);
        } else {
            return '';
        }
    },
    textFormatter: function (value, row, index) {
        if (value) {
            return '<textarea>{0}</textarea>'.format(value);
        } else {
            return '';
        }
    },
    peopleNum: function (value, row, index) {


        if (!value) return '0'
        num = value;
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num))
            num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num * 100 + 0.50000000001);
        cents = num % 100;
        num = Math.floor(num / 100).toString();
        if (cents < 10)
            cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' +
                num.substring(num.length - (4 * i + 3));

        var nun = (((sign) ? '' : '-') + num + '.' + cents);
        return nun.substring(0, nun.length - 3);
    },
    moneyFormatter: function (value, row, index) {
        if (!value) return '0.00'
        num = value;
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num))
            num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num * 100 + 0.50000000001);
        cents = num % 100;
        num = Math.floor(num / 100).toString();
        if (cents < 10)
            cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' +
                num.substring(num.length - (4 * i + 3));
        return (((sign) ? '' : '-') + num + '.' + cents);
    },
    colEnumFormatter: function myfunction(enumdesc) {
        var self = this;
        var format = function (value, row, index) {
            return self.enumFormatter(value, enumdesc);
        }
        return format;
    },
    enumFormatter: function (value, enumdesc) {
        var regex = /\((.*)\)/;
        if (regex.test(enumdesc)) {
            var result = regex.exec(enumdesc);
            var ary = result[1].split(";");
            for (var i = 0; i < ary.length; i++) {
                var aryKey = ary[i].split(",");
                if (value == aryKey[0]) {
                    return aryKey[1];
                }
            }
            return "";
        } else {
            return value;
        }
    },

    getFilters: function () {
        var mySearchForm = $("#mySearchForm");
        var allInput = $("[data-op]", mySearchForm);
        // 加入myQueryForm
        var myQueryForm = $("#myQueryForm");
        var allQueryInput = $("[data-op]", myQueryForm);
        allInput = _.union(allInput, allQueryInput);
        var filters = [];
        for (var i = 0; i < allInput.length; i++) {
            var item = $(allInput[i]);
            var isRepeat = false;
            var value = item.val();
            if (value != "" && value != undefined) {
                for (var j = 0; j < filters.length; j++) {
                    if (item.data("name") == filters[j].name) {
                        filters[j].value2 = value;
                        isRepeat = true;
                    }
                }
                if (!isRepeat) {
                    var op = item.data("op");
                    if (!op) {
                        op = "like";
                    }
                    var dataType = item.data("datatype");
                    if (!dataType) {
                        dataType = "nvarchar";
                    }
                    if (/^\d+-\d+-\d+$/.test(value)) {
                        if (item.attr("isEndDate") == "1") {
                            value = value + " 23:59:59";
                        } else {
                            value = value + " 00:00:00";
                        }
                    }
                    // 枚举是0的话那么不加入
                    if (value == "0") {
                        continue;
                    }

                    if (value == "是") {
                        value = 1;
                    }
                    if (value == "否") {
                        value = 0;
                    }

                    // 是否是多选
                    var options = item.data("options") ? eval('({{0}})'.format(item.data("options"))) : '';
                    if (options && options.multiple == true) {
                        value = item.iCombobox("getValues").join(",");
                        filters.push({ attribute: item.data("name"), operatoer: op, value: value, datatype: dataType, isMultiple: 1 });
                    } else {
                        filters.push({ attribute: item.data("name"), operatoer: op, value: value, datatype: dataType });
                    }

                }
            }
        }
        if (filters.length >= 1) {
            var myFilter = {
                type: "and",
                conditions: filters
            };
            return myFilter;
        }
        return null;
    },

    dealMultipleFilter: function (filter) {
        if (typeof (filter) == "string") {
            filter = JSON.parse(filter);
        }
        // 找出所有是mutil的条件
        var mutilCondtions = _(filter.conditions).filter(["isMultiple", 1]).value();
        // 多个条件才拼接
        if (mutilCondtions.length > 0) {
            for (var i = 0; i < mutilCondtions.length; i++) {
                var values = mutilCondtions[i]["Value"] || mutilCondtions[i]["value"];
                var attribute = mutilCondtions[i]["Attribute"] || mutilCondtions[i]["attribute"];

                var aryValue = values.split(",");
                // 需要把之前的条件删除掉构造
                if (aryValue.length > 1) {
                    _(filter.conditions).remove(['attribute', attribute]).value();
                    // 构造condtions
                    var condtions = [];
                    for (var j = 0; j < aryValue.length; j++) {
                        var copyCondtion = $.dm.deepCopy(mutilCondtions[i]);

                        // 兼容大小写
                        if (copyCondtion.value) {
                            copyCondtion.value = aryValue[j];
                        } else {
                            copyCondtion.Value = aryValue[j];
                        }

                        condtions.push(copyCondtion);
                    }

                    // 加入到下层的filters 拼接成 and (1 or 2 or 3)
                    var orFilters = [{
                        type: "and",
                        innerType: "or",
                        conditions: condtions
                    }];

                    // 递归获取底层的filter 加入filters
                    var myFilter = recursionFilter(filter);

                    // 如果没有condtions那么需要把外层的置为or的条件
                    if (myFilter.conditions.length == 0) {
                        filter = orFilters[0];
                    } else {
                        myFilter.filters = orFilters;
                    }

                }
            }
        }


        function recursionFilter(filterObj) {
            if (filterObj.filters && filterObj.filters[0]) {
                var obj = filterObj.filters[0];
                return recursionFilter(obj);
            } else {
                return filterObj;
            }
        }

        return JSON.stringify(filter);
    },
    // 打开新的tab 
    openNewTab: function (title, url, icons, functionId, number, isAdd) {
        var params = {
            url: url,
            text: title,
            iconCls: icons
        }
        var t = parent.$("#index_tabs");
        if (number) {
            var dom = "";
            for (var i = 0; i < number; i++) {
                dom += "parent.";
            }
            t = eval(dom + 'parent.$("#index_tabs")');
        }
        var $selectedTab = t.iTabs('getSelected');
        var selectedTabOpts = $selectedTab.iPanel('options');
        if (topJUI.config.appendRefererParam && params.url) params.url = appendRefererParam(params.url);
        var iframe = '<iframe src="' + params.url + '" scrolling="auto" frameborder="0" style="width:100%;height:100%;"></iframe>';

        var defaults = {
            id: getRandomNumByDef(),
            refererTab: {},
            title: params.text,
            iframe: topJUI.config.iframe,
            onlyInitParse: true,
            iconCls: 'fa fa-file-text-o',
            border: true,
            fit: true,
            closable: true
        };
        var opts = $.extend(defaults, params);
        var ifOpts = opts.iframe ? { content: iframe } : { href: params.url };
        opts = $.extend(opts, ifOpts);
        if (!opts.iconCls || opts.iconCls.trim() === '') {
            opts.iconCls = 'fa fa-file-text-o';
        }

        if (t.iTabs('exists', opts.title)) {
            t.iTabs('select', opts.title);
        } else {
            var lastMenuClickTime = $.cookie("menuClickTime");
            var nowTime = new Date().getTime();
            if ((nowTime - lastMenuClickTime) >= 500) {
                $.cookie("menuClickTime", new Date().getTime());
                t.iTabs('add', opts);
            } else {
                $.iMessager.show({
                    title: '温馨提示',
                    msg: '操作过快，请稍后重试！'
                });
            }
        }
        if (isAdd == 1) {
            createFunctionSet(functionId, title, url);
        }
        else {
            if (typeof (createFunctionSet) != "undefined" && functionId) {
                createFunctionSet(functionId, title, url);
            }
        }


    },
    donwFile: function (id) {
        var value = $("#" + id).textbox('getValue');
        if (value) {
            if (value.startsWith("http")) {
                window.location.href = value;
            } else {
                window.location.href = "/api/services/app/File/DownFileForUpload?filePath=" + value;
            }
        }
    }

}

// 绑定查找取消事件
$(function myfunction() {
    if ($("#mySearchForm").length >= 1) {
        $('body').unbind('keydown').keydown(function (e) {
            if (e.keyCode == 13) {
                searchQuery();
            }
        }).keydown(function (e) {
            if (e.keyCode == 27) {
                $('#mySearchForm').form('clear')
            }
        });
        $("#mySearchForm").show();
    }
})

jQuery.loader = {
    comboxLoader: function (param, success, error) {
        var q = param.q || '';
        var initCondtions = param.initCondtions || '';

        var selectNames = param.selectNames || '';
        if (param.initQuery && param.q === undefined) {
            q = param.initQuery
        }
        var idField = 'id';
        if (param.idField) {
            idField = param.idField;
        }
        var selStr = idField + ',' + param.comBoxValueName;

        // 需要额外查找其他字段信息
        if (selectNames) {
            selStr += ',' + selectNames;
        }

        var order = 'createTime desc';

        if (param.order) {
            order = param.order;
        }
        var rows = 50;
        if (param.rows) {
            rows = param.rows;
        }
        var data = {
            rows: rows,
            page: 1,
            order: order,
            viewName: param.viewName,
            select: selStr
        };

        if (param.rows) {
            data.rows = param.rows;
        }

        if (param.isDisableFilter) {
            data.isDisableFilter = 1;
        }


        var myComboxFilter = null;
        if (q) {
            myComboxFilter = {
                Type: "and",
                conditions: [{
                    Attribute: param.comBoxValueName,
                    Datatype: "nvarchar",
                    Operatoer: "like",
                    Value: q
                }]
            };
            if (initCondtions) {
                myComboxFilter.conditions = _.union(myComboxFilter.conditions, initCondtions);
            }
        } else if (initCondtions) {
            myComboxFilter = {
                Type: "and",
                conditions: initCondtions
            };
        }

        // 处理过滤条件 用于自定义过滤条件
        if (param.filterDeal) {
            param.filterDeal(myComboxFilter, q);
        }

        if (myComboxFilter) {
            data.filter = JSON.stringify(myComboxFilter);
        }
        var tableName = param.viewName.toLowerCase().replace("view_", "").replace(/_/g, "");
        var options = {
            url: '/api/services/app/' + tableName + '/GetGridDto',
            data: data
        };
        if (param.maskJqSelect) {
            options.maskJqSelect = param.maskJqSelect;
        }
        var abpSuccess = function (result) {
            var items = [];
            if (param.isShowAll && !param.q) {
                items.push({
                    id: '',
                    text: '全部'
                });
            } else {
                // 编辑页面 显示null的选项 GUID 显示默认值 这样更新后端就为null
                if (param.initQuery != undefined && result.rows.length > 0 && !param.q) {
                    if (/[A-F0-9]{8}(-[A-F0-9]{4}){3}-[A-F0-9]{12}/i.test(result.rows[0][idField])) {
                        items.push({
                            id: '00000000-0000-0000-0000-000000000000',
                            text: ''
                        });
                    } else {
                        items.push({
                            id: '',
                            text: ''
                        });
                    }
                }
            }

            if (param.initData) {
                items = _.concat(items, param.initData)
            }
            $.each(result.rows, function (index, item) {
                var optionData = {
                    id: item[idField],
                    text: item[param.comBoxValueName],
                };
                if (param.selectNames) {
                    optionData.objData = item;
                }
                items.push(optionData);
            })
            success(items);
        }
        abp.ajax(options).done(abpSuccess);
    }
}



// 绑定查找取消事件
$(function () {
    if ($("#mySearchForm").length >= 1) {
        $('body').unbind('keydown').keydown(function (e) {
            if (e.keyCode == 13) {
                searchQuery();
            }
        }).keydown(function (e) {
            if (e.keyCode == 27) {
                $('#mySearchForm').form('clear')
            }
        });
        $("#mySearchForm").show();
    } else {
        if ($("#myQueryForm").length >= 1) {
            $('body').unbind('keydown').keydown(function (e) {
                if (e.keyCode == 13) {
                    searchQuery();
                }
            }).keydown(function (e) {
                if (e.keyCode == 27) {
                    $('#myQueryForm').form('clear')
                }
            });
            $("#myQueryForm").show();
        }
    }
})